<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title><tiles:insertAttribute name="title" ignore="true" /></title>
	<link href="/css/jqgrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<form id="excelUploadForm" method="post" enctype="multipart/form-data">
		<table>
        	<tr>
            	<td style="width: 500px;">
                	<div style="border: 1px #A3CBDD solid; width:200px; height: 18px; float: left;">
                    	<input type="text" id="fakeUploadPath" name="fakeUploadPath" readonly="readonly" style="border: 0px; width: 198px; height: 15px;"/>                            		
                    </div>
					<input type="file" id="uploadFile" name="uploadFile" style="opacity: 0; left: 205px; top: 10px; width: 100px; height: 22px; position: absolute; cursor: pointer; filter: alpha(opacity=0); -ms-filter: alpha(opacity=0); -khtml-opacity: 0; -moz-opacity: 0;"/>
					<input type="button" id="btnFakeUploadPath" value="파일첨부" style="width: 95px; height: 20px;"/>
					<br/><br/>
					<button id="btnTransferUploadData">데이터 전송</button>
                </td>
            </tr>
			<tr>
				<td colspan="2">
					<div id="fileSizeArea">파일사이즈 : <span id="fileSize">0</span> Kb</div>
				</td>
			</tr>
        </table>
	</form>
	<table id="uploadGrid"></table>


	<!-- /login-extra -->
	<script src="<c:url value='/js/plugin/json2.js'/>"></script>
	<script src="<c:url value='/js/plugin/jquery-1.7.2.min.js'/>"></script>
    <script src="<c:url value='/js/plugin/jquery.form.js'/>"></script>
    <script src="<c:url value='/js/plugin/grid/jquery.jqGrid.min.js'/>"></script>
    <script src="<c:url value='/js/plugin/grid/i18n/grid.locale-kr.js'/>"></script>
	<script type="text/javascript">
	$(document).ready(function(){
		initEvent();
		initUploadGrid();
	});
	function initEvent(){
		//파일명 맵핑
        $("#uploadFile").change(function() {
        	var fileName = $("#uploadFile").val();
        	var splitFileName = fileName.split("\\");
        	$("#fakeUploadPath").val(splitFileName[splitFileName.length-1]);
        	$("#excelUploadForm").attr("action", "fileInfo.file").submit();
        });
        
		//동적 파일정보 추출 및 그리드 맵핑
        $("#excelUploadForm").ajaxForm( {
        	iframe: "true",
        	type: "POST",
        	dataType: "text",
        	cache: false,
        	modal: true,
        	async : false,
        	success: function (response)
        	{
        		console.log(response);
        		if(response != null || response != ""){
        			var data = JSON.parse(response);
            		var size = data.file[0].sizeKB;
            		$("#fileSize").html(size);
            		//검색된 첫번째줄은 해더로 취급
            		var uploadData = [];
            		for(var i = 2 ; i < data["excel"][0].length ; i++){
            			uploadData[i - 1] = data["excel"][0][i];
            		}
                    $("#uploadGrid").jqGrid('clearGridData').jqGrid('setGridParam', { data: uploadData, datatype: 'local' }).trigger('reloadGrid');
        		}
        	}
       	} );
        
		//데이터 전송 및 전송결과 그리드 맵핑
        $("#btnTransferUploadData").click(function(){
    		$.ajax({
    			type: "POST"
    			, url: "/storeCompanyForExcel.json"
    			, data: {
    				json: getJsonListStr('uploadGrid')
    			}
    		}).done(function( msg ) {
                $("#uploadGrid").jqGrid('clearGridData').jqGrid('setGridParam', { data: msg["excel"], datatype: 'local' }).trigger('reloadGrid');
    		});
    		return false;
        });
	}
	
	//그리드 셋팅
    function initUploadGrid(){
        $("#uploadGrid").jqGrid({
            datatype: 'json', //데이터형태 
            colNames: ['miss', '사업자구분', '사업자번호', '사업자명', '대표자', '사업자주소', '업종', '업태','업체관리명', '전송'], //헤더 
            colModel: [ //컬럼속성
            {
                name: 'miss',
                index: 'miss',
                width: 70,
                hidden: true,
                sortable: false
            }, {
                name: 'excel_0',
                index: 'excel_0',
                width: 70,
                sortable: false,
                align: 'center'
            }, {
                name: 'excel_1',
                index: 'excel_1',
                width: 65,
                sortable: false
            }, {
                name: 'excel_2',
                index: 'excel_2',
                width: 70,
                sortable: false
            }, {
                name: 'excel_3',
                index: 'excel_3',
                width: 55,
                sortable: false
            }, {
                name: 'excel_4',
                index: 'excel_4',
                width: 80,
                sortable: false
            }, {
                name: 'excel_5',
                index: 'excel_5',
                width: 70,
                sortable: false
            }, {

                name: 'excel_6',
                index: 'excel_6',
                width: 50,
                sortable: false
            }, {
                name: 'excel_7',
                index: 'excel_7',
                width: 50,
                sortable: false
            }, {
                name: 'result',
                index: 'result',
                formatter: transferFormatter,
                width: 50,
                editable: true,
                sortable: false
            }],
            multiselect: false, //multi select 를 위한 check box 사용여부 
            jsonReader: {
                root: "root",
                page: "page",
                total: "total",
                records: "records",
                repeatitems: false,
                id: "row_id"
            },
            footerrow: false,
            userDataOnFooter: false,
            cellEdit: false, //그리드의 edit 모드 설정 
            shrinkToFit: false, //width 가 고정되어있는 경우 가로스크롤 사용여부
            cellsubmit: 'clientArray', //jqGrid의 auto submit 기능을 제거
            rownumbers: true,
            mtype: 'POST',
            postData: "",
            beforeRequest: function() {
            	
            },
            loadComplete: function() {
            },
            afterInsertRow : function(rowid, aData) {
            },
            afterEditCell: function(rowid, name, value, iRow, iCol) {
            },
            afterSaveCell: function(rowid, name, val, iRow, iCol){
            }
        });
    }
	//성공/실패/중복 여부 체크 Formatter
	function transferFormatter(cellvalue, options, rowObjet){
		if(cellvalue == "T"){
			return "성공";
		}
		if(cellvalue == "F"){
            return "실패";
        }
		if(cellvalue == "D"){
            return "중복";
        }
		else{
			return "대기";
		}
	}
	function getJsonListStr(gridId, rowId){
	    var jsonText = '';
	    jsonText += '{';
	    jsonText += 'root:';
	    jsonText += '[';
	    if (!rowId) {
	        // case 1: row id 가 비어있는경우 - (1) check box로 선택된 행을 리턴 (2)check 된행이 없다면
	        // 전체 행을 리턴
	        var selectedIds = $("#" + gridId).jqGrid('getGridParam', 'selarrrow');
	        if (selectedIds.length > 0) {
                for (var i = 0; i < selectedIds.length; i++) {
                    jsonText += getJsonRowStr(gridId, selectedIds[i]);
                    if(i < selectedIds.length - 1){
                        jsonText += ',';
                    }
                }
	        }
	        else {
	        	selectedIds = $("#" + gridId).getDataIDs();
	            for(var i = 0 ; i < selectedIds.length ; i++) {
	            	jsonText += getJsonRowStr(gridId, selectedIds[i]);
	            	if(i < selectedIds.length - 1){
	                    jsonText += ',';
	            	}
	            }
	        }
	    }
	    else {
	        // case 2: row id 가 있는경우 - (1) 파라메터 row id 에 해당하는 행을 리턴
	        jsonText += getJsonRowStr(gridId, rowId);
	    }
	    
	    jsonText += ']';
	    jsonText += '}';
	    return jsonText;
	}

	/**
	 * gridId에 해당하는 테이블에서 rowId 에 해당하는 row를 json text 형태로 반환 한다.
	 */
	function getJsonRowStr(gridId, rowId){
	    var rowData = getGridRowData(gridId, rowId);
	    var jsonText = '';
	    
	    jsonText += '{';
	    
	    for (var item in rowData) {
	        jsonText += "'" + item + "'" + ':' + "'" + rowData[item].replace(/'/g,'"') + "'";
	        jsonText += ',';
	    }
	    
	    jsonText = jsonText.substring(0, jsonText.length - 1);
	    
	    jsonText += '}';
	    return jsonText;
	}
	
	/**
	 * Grid getRowData 할 때, <input type="text".../> 태그 딸려오는 문제 보완
	 * @param rowid
	 */
	function getGridRowData(gridId, rowId){
	    var rowData = $("#" + gridId).getRowData(rowId);
	    $("#" + rowId).find("input:text").each(function(e){
	        rowData[$(this).attr("id").replace(rowId + "_", "")] = $(this).val();
	    });
	    return rowData;
	}
	</script>
</body>
</html>